package com.demo.aop.profile;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StopWatch;

import java.lang.reflect.Method;

/**
 * 描述：一个环绕的计时器
 *
 * @author lida
 * @time 2019/10/23 10:17
 */
public class ProfilingInterceptor implements MethodInterceptor {
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		//时间的计时器
		StopWatch sw = new StopWatch();
		sw.start(invocation.getMethod().getName());

		Object re = invocation.proceed();
		sw.stop();
		dumpInfo(invocation, sw.getTotalTimeMillis());
		return null;
	}

	private void dumpInfo(MethodInvocation invocation, long totalTimeMillis) {
		Method m = invocation.getMethod();
		Object target = invocation.getThis();
		Object[] args = invocation.getArguments();

		System.out.println("Method Name: " + m.getName());
		System.out.println("On Object of type: " + target.getClass().getName());
		System.out.println("with arguments:");
		for (Object arg : args) {
			System.out.print("[" + arg + "]");
		}
		System.out.print("\n");
		System.out.println("Took: " + totalTimeMillis + "ms");
	}
}
